<template>
    <div class="opener" @click="getProductInfo">
        <span style="padding: 6px; color: #fff">飞豹助手已载入 {{JSON.stringify(videoList)}}</span>
    </div>
</template>

<script>
import getData from './getData'
import { ElMessage, ElNotification } from 'element-plus'
import VideoLinkDownload from './VideoLinkDownload.vue'
import MessageView from './MessageView.vue'
import VideoBlock from './VideoBlock.vue'
import ReviewListMessageView from './ReviewListMessageView.vue'
import qrcode from 'yaqrcode'
import syncLoop from './sync-loop'
import { getAsinFromLocation } from './utils'

const TIMER_DELAY = 5000
const NOT_FOUND_INFO = "Sorry! We couldn't find that page. Try searching or go to Amazon's home page."
// const NOT_FOUND_INFO = '很抱歉。您输入的网址不是我们网站上的有效网页。'

const isExpired = () => {
    return Array.from(document.querySelectorAll('img')).map(item => item.alt).join('').indexOf(NOT_FOUND_INFO) !== -1
    // const notFoundEl = document.querySelector('body > center > table > tbody > tr > td:nth-child(2)')
    // if(notFoundEl && notFoundEl.textContent.indexOf(NOT_FOUND_INFO) !== -1) {
    //     return true
    // }
    // return false
}

export default {
    data() {
        return {
            requestBody: {
                hello: 'world',
                base64Code: undefined,
                videoList: []
            }
        }
    },
    components: {
    },
    methods: {
        updateProductInfo(data) {
            // AEO库中存的是父ASIN，但页面抓取的是子ASIN，导致无法入库，所以重新获取地址栏中的父ASIN（realASIN）进行入库
            // const realAsin = window.location.href.match(/dp\/(B0\w+)/)[1]
            const realAsin = getAsinFromLocation()
            chrome.runtime.sendMessage({
                // asin: data.asin,
                asin: realAsin,
                title: data.title,
                shopName: data.shop.name,
                photoUrl: data.image,
                salePrice: data.price,
                // saleRank: JSON.stringify({
                //     topRank: data.topRank,
                //     subRank: data.subRank
                // }),
                shopUrl: data.shop.link,
                saleRank: JSON.stringify([
                    data.topRank,
                    data.subRank
                ]),
                sellerId: data.sellerId
            }, ({req, data: res}) => {
                console.log('update res', res)
                this.requestBody = req
                if(res.result === 'success') {
                    ElNotification({
                        title: '数据入库成功 - 飞豹助手 1.3',
                        type: 'success',
                        duration: 0,
                        showClose: true,
                        message: <MessageView data={data} />
                    })
                    this.closeWindow()
                } else {
                    console.error('入库失败', res)
                    ElNotification({
                        title: `入库失败 - ${data.msg}`,
                        type: 'error',
                        showClose: true,
                        duration: 0,
                        message: <MessageView data={data} />
                    })
                }
            })
        },
        getVideoLink() {
            const videoThumbnailEl = document.querySelector('#altImages .videoThumbnail .a-button-thumbnail > span > input')
            if(videoThumbnailEl) {
                videoThumbnailEl.onmouseover = function() {
                    const videoSrc = document.querySelector('video').src
                    if(videoSrc.endsWith('.mp4')) {
                        ElNotification({
                            title: '视频下载',
                            type: 'success',
                            showClose: true,
                            duration: 0,
                            message: <VideoLinkDownload link={videoSrc}/>
                        })
                    } else {
                        ElMessage({
                            type: 'warning',
                            message: '未获取到视频链接，再试一次哦～😕',
                        })
                    }
                }
            }
        },
        closeWindow() {
            // setTimeout(() => {
            //     window.close()
            // }, TIMER_DELAY * 5);
        },
        removeExpiredProdict() {
            chrome.runtime.sendMessage({
                msg: 'removeAsin',
                data: getAsinFromLocation()
            }, ({msg}) => {
                // alert('delete ok: ' + JSON.stringify(res))
                if(msg === 'deleteok') {
                    ElNotification({
                        title: '警告',
                        duration: 0,
                        showClose: true,
                        type: 'error',
                        message: 'ASIN过期，已从数据库中删除'
                    })
                    this.closeWindow()
                }
            })
            // axios.post(`${host}/web.do?fn=setstate`, {
            //     asin: getAsinFromLocation(),
            //     state: 2
            // }).then((res) => {
            //     alert(JSON.stringify(res))
            // })
        },
        showReviewList() {
            const reviewListEl = document.querySelectorAll('#cm_cr-review_list > div.a-section.review.aok-relative')
            const totalEl = document.querySelector('#filter-info-section > div')
            let total
            if(totalEl) {
                total = parseInt(totalEl.textContent.trim().match(/([,\d]+) with reviews/)[1].replace(',', ''))
            }
            // next #cm_cr-pagination_bar > ul > li.a-last > a
            // prev #cm_cr-pagination_bar > ul > li:nth-child(1) > a
            // #cm_cr-pagination_bar > ul > li.a-last > a
            // const nextPageEl = document.querySelector('#cm_cr-pagination_bar > ul > li > a')
            // const paginationLink = Array.from(document.querySelectorAll('#cm_cr-pagination_bar > ul > li > a')).map(item => item.href).pop()
            const paginationLinkEl = document.querySelector('#cm_cr-pagination_bar > ul > li:last-child > a')
            // alert(paginationLink)
            let openPageTimer, paginationLink
            if(paginationLinkEl) {
                paginationLink = paginationLinkEl.href
                openPageTimer = setTimeout(() => {
                    window.open(paginationLink, "_blank")
                }, TIMER_DELAY);
            } else {
                clearTimeout(openPageTimer)
                ElMessage({
                    message: '评论抓取完毕',
                    duration: 0,
                    showClose: true,
                    type: 'success'
                })
            }
            // console.log('nextPageEl', nextPageEl, paginationLink)
            let nextPageLinkTempl
            if(paginationLink) {
                nextPageLinkTempl = paginationLink.replace(/ref=cm_cr_arp_d_paging_btm_\d+/, 'ref=cm_cr_arp_d_paging_btm_next_PAGE').replace(/pageNumber=\d+/, 'pageNumber=PAGE')
                // nextPageLinkTempl = nextPageEl.href.replace(/ref=cm_cr_arp_d_paging_btm_\d+/, 'ref=cm_cr_arp_d_paging_btm_next_PAGE').replace(/pageNumber=\d+/, 'pageNumber=PAGE')
            }
            const reviewList = Array.from(reviewListEl).map(item => {
                // console.log('item', item)
                let text
                const reviewEl = item.querySelector('div.a-row.a-spacing-small.review-data > span > span')
                const profileEl = item.querySelector('div:nth-child(1) > a')
                if(reviewEl) {
                    text = reviewEl.innerText.trim()
                }
                const profileId = profileEl.href.match(/account.(\w+)\//)[1]
                const starsTitle = item.querySelector('div:nth-child(2) > a:nth-child(1)').title
                const stars = parseInt(starsTitle.split('out')[0])
                const reviewTitleEl = item.querySelector('div:nth-child(2) > a.a-size-base.a-link-normal.review-title.a-color-base.review-title-content.a-text-bold > span')
                const title = reviewTitleEl.textContent
                const videoEl = item.querySelector('div[data-video-url]')
                let videoUrl, videoThumbnail
                if(videoEl) {
                    videoUrl = videoEl.dataset.videoUrl.replace('.hls.m3u8', '.mp4.480.mp4')
                    videoThumbnail = videoEl.dataset.thumbnailUrl
                }
                return {
                    text,
                    profileName: profileEl.querySelector('div.a-profile-content > span').textContent,
                    profileId,
                    stars,
                    title,
                    videoUrl,
                    videoThumbnail
                }
            })
            ElNotification({
                title: `评论数据抓取（${total}）`,
                type: 'success',
                duration: 0,
                showClose: true,
                message: <ReviewListMessageView data={reviewList} total={total} next-page-link-templ={nextPageLinkTempl} />
            })
            this.closeWindow()

        },
        getProductInfo() {
            // const expired = Array.from(document.querySelectorAll('img')).map(item => item.alt).join('').indexOf(NOT_FOUND_INFO) !== -1
            const saveInDb = false
            if(isExpired()) {
                // alert('过期了')
                this.removeExpiredProdict()
            } else {
                const data = getData()
                console.log('data', data, saveInDb)
                this.videoList = data.videoList
                if(saveInDb) {
                    this.updateProductInfo(data)
                } else {
                    ElNotification({
                        title: '抓取数据成功 - 飞豹助手 1.3',
                        type: 'success',
                        duration: 0,
                        showClose: true,
                        message: <MessageView data={data} />
                    })
                }
            }
            // this.closeWindow()

        }
    },
    mounted() {
        // this.getVideoLink()

        const customReviewEl = document.querySelector('#cm_cr-product_info > div > div.a-text-left.a-fixed-left-grid-col.reviewNumericalSummary.celwidget.a-col-left > div.a-row.a-spacing-mini.customerReviewsTitle > h2')
        const titleEl = document.querySelector('#productTitle')
        if(customReviewEl) {
            this.showReviewList()
        }
        if(titleEl) {
            this.getProductInfo()
        }

        setTimeout(() => {
            const mainVideoThumbnailEl = document.querySelector("#a-autoid-9 > span > input")
            console.log('mainVideoThumbnailEl', mainVideoThumbnailEl)
            if(mainVideoThumbnailEl) {
                mainVideoThumbnailEl.onmouseover = () => {
                    // alert(999)
                    const mainVideoThumbnailImageEl = document.querySelector("#main-video-container #airy-slate-postmedia")
                    console.log("mainVideoThumbnailImageEl", mainVideoThumbnailImageEl)
                    // console.log('mainVideoThumbnailImageEl.style', mainVideoThumbnailImageEl.style)
                    let mainVideoThumbnailImageUrl
                    if(mainVideoThumbnailImageEl.style && mainVideoThumbnailImageEl.style.backgroundImage) {
                        mainVideoThumbnailImageUrl = mainVideoThumbnailImageEl.style.backgroundImage.match(/https:.*jpg/)[0]
                    }
                    console.log('mainVideoThumbnailImageUrl', mainVideoThumbnailImageUrl)
                    const mainVideoEl = document.querySelector('video')
                    const videoSrc = mainVideoEl.src
                    if(videoSrc.endsWith('mp4')) {
                        // window.open(videoSrc, '_blank')
                        const videoUrlBase64 = qrcode(videoSrc)
                        console.log('videoUrlBase64', videoUrlBase64)
                        ElNotification({
                            title: "主视频",
                            message: (
                                <div>
                                    <VideoBlock
                                        src={videoSrc}
                                        videoUrlBase64={videoUrlBase64}
                                        thumbnailUrl={mainVideoThumbnailImageUrl} />
                                </div>
                            )
                        })
                    } else {
                        ElMessage({
                            message: "未检测到视频链接，请再试一次"
                        })
                    }
                }
            }
        }, 1000);

        // const NOT_FOUND_INFO = "Sorry! We couldn't find that page. Try searching or go to Amazon's home page."
        // const expired = Array.from(document.querySelectorAll('img')).map(item => item.alt).join('').indexOf(NOT_FOUND_INFO) !== -1
        if(isExpired()) {
            this.removeExpiredProdict()
        }

        chrome.runtime.sendMessage('qryASIN', ({msg, updateAsinList = []}) => {
            console.log('qryASIN ok', msg) // noresult1
            if(updateAsinList.length === 0) {
                ElNotification({
                    title: '无ASIN需要更新',
                    type: 'success',
                    duration: 0
                })
            } else {
                // window.open(`https://www.amazon.com/dp/B09D31XNW7?th=1&psc=1`)
                console.log("window.location.href === 'https://www.amazon.com/'", window.location.href === 'https://www.amazon.com/')
                if(window.location.href === 'https://www.amazon.com/') {
                    // updateAsinList.forEach(item => {
                    //     // console.log('open asin to fetch', item.asin)
                    //     window.open(`https://www.amazon.com/dp/${item.asin}?th=1&psc=1`)
                    // })
                    // for(const item of updateAsinList) {

                    
                    syncLoop(updateAsinList, item => {
                        // alert('sync:::: ' + item)
                        window.open(`https://www.amazon.com/dp/${item.asin}?th=1&psc=1`)
                    }, TIMER_DELAY)

                    // }
                }
            }
            // if(msg === 'update') {
            //     ElNotification({
            //         title: '自动更新成功',
            //         type: 'success'
            //     })
            // } else if(msg === 'noresult1') {
            //     ElNotification({
            //         title: '无ASIN需要更新1',
            //         type: 'success',
            //         duration: 0
            //     })
            // } else if(msg === 'noresult2') {
            //     ElNotification({
            //         title: '无ASIN需要更新2',
            //         type: 'success',
            //         duration: 0
            //     })
            // } else {
            //     console.log('updateAsinList', updateAsinList)
            // }
        })

        // alert('qryASIN')
        // const qryASINApi = `${host}/web.do?fn=qryASIN`
        // axios({
        //     url: qryASINApi,
        //     method: 'POST',
        //     data: {
        //         "state": 0,
        //         "daysUpdate": 1,
        //         "page": 1,
        //         "pagesize": 1000
        //     }
        // }).then(res => {
        //     console.log('')
        // })

        // axios({
        //     url: `${host}/web.do?fn=qryASIN`,
        //     method: 'POST',
        //     data: {
        //         "state": 0,
        //         "daysUpdate": 1,
        //         "page": 1,
        //         "pagesize": 1000
        //     }
        // }).then(res => {
        //     console.log('qryASIN', res)
        // })

    }
}
</script>

<style scoped>
</style>